import requests
from openai import OpenAI
import re

client = OpenAI(
    api_key="sk-hbxoxotmmfsnsbcsvmeryrbjvfdqltpicciktjrjkspdhfxo",  # 从https://cloud.siliconflow.cn/account/ak获取
    base_url="https://api.siliconflow.cn/v1"
)


# 天气查询工具
def get_weather(city: str):
    api_key = "50c9079882924700a87112756252906"
    base_url = "http://api.weatherapi.com/v1/current.json"
    params = {'key': api_key, 'q': city, 'aqi': 'no'}
    response = requests.get(base_url, params=params)

    if response.status_code == 200:
        data = response.json()
        weather = data['current']['condition']['text']
        temperature = data['current']['temp_c']
        return f"The weather in {city} is {weather} with a temperature of {temperature}°C."
    else:
        return f"Could not retrieve weather information for {city}."


# 计算器工具
def calculator(num1: float, num2: float, operation: str):
    print(f"num1 {num1} {operation} num2 {num2}")
    if operation == "addition":
        return num1 + num2
    elif operation == "subtraction":
        return num1 - num2
    elif operation == "multiplication":
        return num1 * num2
    elif operation == "division":
        if num2 != 0:
            return num1 / num2
        else:
            return "Error: Division by zero is not allowed."
    else:
        return "Error: Unsupported operation."


# 工具列表
tools = [
    {
        'type': 'function',
        'function': {
            'name': 'get_weather',
            'description': 'Get the current weather for a given city.',
            'parameters': {
                'type': 'object',
                'properties': {
                    'city': {'type': 'string', 'description': 'The name of the city to query weather for.'},
                },
                'required': ['city'],
            },
        }
    },
    {
        'type': 'function',
        'function': {
            'name': 'calculator',
            'description': 'Perform basic mathematical operations between two numbers.',
            'parameters': {
                'type': 'object',
                'properties': {
                    'num1': {'type': 'number', 'description': 'The first number for the operation.'},
                    'num2': {'type': 'number', 'description': 'The second number for the operation.'},
                    'operation': {'type': 'string', 'enum': ['addition', 'subtraction', 'multiplication', 'division'], 'description': 'The mathematical operation to perform.'},
                },
                'required': ['num1', 'num2', 'operation'],
            },
        }
    }
]


def function_call_playground(prompt):
    instruction = "Please ensure the city names are in English when using the weather tool. Additionally, ensure valid inputs are provided for calculator operations."
    messages = [{'role': 'system', 'content': instruction}, {'role': 'user', 'content': prompt}]

    response = client.chat.completions.create(
        model="deepseek-ai/DeepSeek-V2.5",
        messages=messages,
        temperature=0.01,
        top_p=0.95,
        stream=False,
        tools=tools
    )

    func1_name = response.choices[0].message.tool_calls[0].function.name
    func1_args = response.choices[0].message.tool_calls[0].function.arguments
    func1_out = eval(f'{func1_name}(**{func1_args})')
    return func1_out
    # tool_calls = response.choices[0].message.tool_calls
    # if tool_calls:
    #     func_name = tool_calls[0]['function']['name']
    #     func_args = tool_calls[0]['function']['arguments']
    #
    #     if func_name == "get_weather":
    #         city = func_args.get("city")
    #         if not city or not re.match(r'^[a-zA-Z\s]+$', city):
    #             return f"Error: The city name '{city}' provided by the model is invalid."
    #         return get_weather(city)
    #     elif func_name == "calculator":
    #         num1 = func_args.get("num1")
    #         num2 = func_args.get("num2")
    #         operation = func_args.get("operation")
    #         return calculator(num1, num2, operation)
    #     else:
    #         return f"Error: Unknown tool '{func_name}'."
    # else:
    #     return "Error: No tool calls were generated by the AI."


# 示例
prompt_weather = "上海的天气怎么样"
prompt_calculator = "请帮我计算21乘以97"
print(function_call_playground(prompt_weather))
print(function_call_playground(prompt_calculator))